using System;
using System.IO;
using System.Text.RegularExpressions;

namespace UploadServer.middlewares
{
    public class JwtPayload
    {
        /// <summary>
        /// 过期时间戳
        /// </summary>
        public long exp { get; set; }

        /// <summary>
        /// app名称
        /// </summary>
        public string app { get; set; }

        /// <summary>
        ///  100kb,2.5mb等等
        /// </summary>
        public string size { get; set; }

        private long? _byteSize;

        /// <summary>
        /// 后缀， .exe;.zip
        /// </summary>
        public string exts { get; set; }

        public string validate()
        {
            if (string.IsNullOrWhiteSpace(app))
            {
                return "JWT no 'app' but needed";
            }

            if (Regex.IsMatch(app, "[^0-9A-Za-z_-]", RegexOptions.Multiline))
            {
                return "JWT 'app' invalid";
            }

            if (!string.IsNullOrEmpty(size))
            {
                if (size.Length > 2)
                {
                    var strNum = size.Substring(0, size.Length - 2);

                    if (long.TryParse(strNum, out var num))
                    {
                        if (size.EndsWith("kb", StringComparison.OrdinalIgnoreCase))
                        {
                            _byteSize = num * 1024;
                        }
                        else if (size.EndsWith("mb", StringComparison.OrdinalIgnoreCase))
                        {
                            _byteSize = num * 1024 * 1024;
                        }
                        else
                        {
                            return "JWT 'size' invalid";
                        }
                    }
                    else
                    {
                        return "JWT 'size' invalid";
                    }
                }
                else
                {
                    return "JWT 'size' invalid";
                }
            }

            return null;
        }

        public long? GetByteSize()
        {
            return _byteSize;
        }
    }
}